package com.yuke.cloud.service.smc.controller.frontend;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yuke.cloud.common.base.enums.ErrorCodeEnum;
import com.yuke.cloud.common.core.support.BaseController;
import com.yuke.cloud.common.util.wrapper.WrapMapper;
import com.yuke.cloud.common.util.wrapper.Wrapper;
import com.yuke.cloud.service.api.omc.service.OmcOrderFeignApi;
import com.yuke.cloud.service.api.uac.dto.UserInfoDto;
import com.yuke.cloud.service.api.uac.service.UacUserFeignApi;
import com.yuke.cloud.service.api.wmc.dto.StorageSpecInfoDto;
import com.yuke.cloud.service.smc.dto.ShopDto;
import com.yuke.cloud.service.smc.entity.Shop;
import com.yuke.cloud.service.smc.entity.ShopRecommend;
import com.yuke.cloud.service.smc.exceptions.SmcBizException;
import com.yuke.cloud.service.smc.service.ShopRecommendService;
import com.yuke.cloud.service.smc.service.ShopService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
* Created by wg on 2018/09/07.
*/
@Slf4j
@Api(value = "WEB - ShopController", tags = "处理Shop相关请求", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@RestController
@RequestMapping("/mall/shop")
public class MallShopController extends BaseController {
    @Resource
    private ShopService shopService;
    @Resource
    private UacUserFeignApi uacUserFeignApi;
    @Resource
    private OmcOrderFeignApi omcOrderFeignApi;
    @Resource
    private ShopRecommendService shopRecommendService;

    @Value("${yuke.shop.deliver_distance}")
    private Integer deliverDistance;



    @GetMapping("/app/nearShop")
    @ApiOperation(httpMethod = "GET", value = "获取附近所有店铺")
    public Wrapper<List<ShopDto>> findNearShops(@RequestParam("longitude") String longitude, @RequestParam("latitude") String latitude) {
        if (longitude == null || latitude == null) {
            return null;
        }
        List<ShopDto> shops = shopService.findNearShops(longitude, latitude, this.deliverDistance);
        return WrapMapper.ok(shops);
    }

    //192.168.3.121:7979/smc/mall/shop/app/findNearShopsForRegist?longitude=114.388644&latitude=30.494942
    @GetMapping("/app/findNearShopsForRegist")
    @ApiOperation(httpMethod = "GET", value = "获取附近所有店铺")
    public Wrapper<List<ShopDto>> findNearShopsForRegist(@RequestParam("longitude") String longitude,
                                                         @RequestParam("latitude") String latitude) {
        if (longitude == null || latitude == null) {
            return null;
        }
        PageHelper.startPage(1, 10);
        List<ShopDto> shops = shopService.findNearShops(longitude, latitude, this.deliverDistance);
        //PageInfo pageInfo = new PageInfo(shops);
        return WrapMapper.ok(shops);
    }
    /**
     * add by wg 20190506 根据用户所在位置经纬度及userId获取附近店铺及推荐店铺，推荐店铺放在首位返回
     * @param longitude
     * @param latitude
     * @param userId
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/app/nearShopsAndReferenceShop")
    @ApiOperation(httpMethod = "GET", value = "分页获取附近店铺及推荐店铺，推荐店铺在首位")
    public Wrapper<PageInfo<ShopDto>> findNearShops(@RequestParam("longitude") String longitude, @RequestParam("latitude") String latitude,
                                                @RequestParam(value = "userId", required = false) Long userId,  // 通过userId找出对应的推荐店铺ID
                                                @ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                                @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size) {
        if (longitude == null || latitude == null) {
            return WrapMapper.error("经纬度不能为空");
        }

        PageHelper.startPage(page, size);
        Integer aaa = 999999999;//this.deliverDistance
        List<ShopDto> shops = shopService.findNearShopsAndReferenceShop(longitude, latitude, aaa, userId);

        if(shops==null||shops.size()<=0){

            ArrayList<Long> shopIds = new ArrayList<>();
            shopIds.add((long)1);
            List<ShopDto> shopDtos = shopService.findByIds(shopIds);

            PageInfo pageInfo = new PageInfo(shopDtos);
            return WrapMapper.ok(pageInfo);
        }
        //如果用户为管理员身份显示全部，否则显示5条
        if (userId != null){
            Wrapper<UserInfoDto> userInfoDto =  uacUserFeignApi.getUserInfoByUserId(userId);
            if (userInfoDto.error()) {
                log.error("--- uacUserFeignApi.getUserInfoByUserId(shop.getUserId())内部异常，参数：{} ---", userId);
                throw new SmcBizException(ErrorCodeEnum.GL99990002);
            }
            Byte typeId = userInfoDto.getResult().getType();


            if(!typeId.equals((byte)4)){
                shops = shops.subList(0, 5);
            }
        }else{
            shops = shops.subList(0, 5);
        }

        PageInfo pageInfo = new PageInfo(shops);
        return WrapMapper.ok(pageInfo);
    }

    /**
     * 获取附近团购点信息
     * @param longitude
     * @param latitude
     * @return
     */
    @GetMapping("/app/findNearShopTeam")
    @ApiOperation(httpMethod = "GET", value = "获取附近所有店铺")
    public Wrapper<List<ShopDto>> findNearShopTeam(@RequestParam("longitude") String longitude, @RequestParam("latitude") String latitude) {
        if (longitude == null || latitude == null) {
            return null;
        }
        List<ShopDto> shops = shopService.findNearShopTeam(longitude, latitude, this.deliverDistance);
        return WrapMapper.ok(shops);
    }

    /**
     * 查看当前团长信息
     * @param shopId
     * @return
     */
    @GetMapping("/app/{shopId}")
    @ApiOperation(httpMethod = "GET", value = "根据ID获取具体信息")
    public Wrapper<ShopDto> detail(@ApiParam(name = "shopId", value = "记录id") @PathVariable Long shopId) {

        Shop shop = shopService.selectByKey(shopId);
        if (shop == null){
            return WrapMapper.error("未找到团长信息！");
        }
        //统计有多少人在该团长处下过单
        Integer number = omcOrderFeignApi.countTeamIntentNumber(shop.getUserId());

        ShopDto shopDto = new ShopDto();
        BeanUtils.copyProperties(shop,shopDto);
        shopDto.setIntentNumber(number);

        //获取用户名称
        Wrapper<UserInfoDto> wrapMapper = uacUserFeignApi.getUserInfoByUserId(shop.getUserId());
        if (wrapMapper.getCode() == 200 ){
            shopDto.setUserName(wrapMapper.getResult().getLoginName());
        }
        return WrapMapper.ok(shopDto);
    }

    /**
     * 常用团长信息
     * @param userId
     * @return
     */
    @GetMapping("/app/findUsedShopTeam")
    @ApiOperation(httpMethod = "GET", value = "根据ID获取具体信息")
    public Wrapper<List<ShopDto>> findUsedShopTeam(@RequestParam(value = "userId") Long userId) {
        if (userId == null ) {
            return null;
        }
        List<ShopDto> shops = shopService.findUsedShopTeam(userId);
        return WrapMapper.ok(shops);
    }

    @PostMapping("/recommend/condition")
    @ApiOperation(httpMethod = "POST", value = "店铺商品审核,根据店铺状态为1：已申请贩卖，正在审核中，店铺名称或商品名称获取店铺商品")
    public Wrapper<PageInfo<StorageSpecInfoDto>> getListByCondition(@ApiParam(name = "id", value = "记录id") @RequestBody(required = false) ShopRecommend shopRecommend,
                                                                    @ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                                                    @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size) {
        PageHelper.startPage(page, size);
        List<StorageSpecInfoDto> list = shopRecommendService.getListByCondition(shopRecommend);
        PageInfo pageInfo = new PageInfo(list);
        return WrapMapper.ok(pageInfo);
    }
}
